<template>
  <div>
   <div class="canvas-box">
      <canvas canvas-id="qrCodeCanvas" class="qr-code-canvas" disable-scroll="true" @touchmove.prevent @mousewheel.prevent></canvas>
   </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
      }
    },
    onShow() {
      this.drawQrCode()
    },
    mounted() {
      this.drawQrCode()
    },
    onReady() {
  
    },
    props: {
      codeUrl: {
        type: String,
        default: ''
      }
    },
    methods: {
      drawQrCode() {
        const that = this
        // canvas 使用的是px，如果要适应屏幕需要转化
        let rpx = wx.getSystemInfoSync().windowWidth / 375
        wx.showToast({
          title: '图片生成中',
          icon: 'loading'
        })
        const context = wx.createCanvasContext('qrCodeCanvas')
        // 清除画布，防止层叠
        context.clearRect(0, 0, 240 * rpx, 300 * rpx)
        context.setFillStyle('#ffffff')
        context.fillRect(0, 0, 240 * rpx, 300 * rpx)
        wx.downloadFile({
          url: that.codeUrl,
          success: function(wxaCode) {
            context.drawImage(wxaCode.tempFilePath, 20 * rpx, 20 * rpx, 200 * rpx, 200 * rpx)
            context.draw(true)
            wx.hideToast()
          }
        })
        context.setFillStyle('#333333')
        // context.font = 'normal bold 12px'
        context.setFontSize(12)
        context.fillText('扫描二维码进入微信官方主播端', 40 * rpx, 250 * rpx)
        context.setFillStyle('#333333')
        context.setFontSize(12)
        context.fillText('创建直播间后可导入该商品', 60 * rpx, 270 * rpx)
      },
      saveToAlbum: function(canvasId) {
        const that = this
        wx.canvasToTempFilePath({
          canvasId: canvasId,
          success: (res) => {
            const filePath = res.tempFilePath
            if (filePath) {
              wx.saveImageToPhotosAlbum({
                filePath: filePath,
                success: (res) => {
                  wx.showToast({ title: '保存成功' })
                },
                fail: function(err) {
                  if (err.errMsg.indexOf('cancel') !== -1) return
                  wx.showModal({
                    content: '保存图片需要访问你的相册',
                    success(res) {
                      if (res.confirm) {
                        that.$pt.openSetting()
                      } else if (res.cancel) {
                        console.log(err)
                      }
                    }
                  })
                }
              })
            }
          }
        })
      }
    }
  }
</script>

<style scoped>
.qr-code-canvas {
  width: 240px;
  height: 300px;
}
</style>
